import 'dart:math';

import 'package:sleep/single/filter/base_filter.dart';

class OutlierFilter extends BaseFliter {
  final double max;
  final double min;

  OutlierFilter(this.max, this.min);

  @override
  List<double> fliter(List<double> data) {
    double mean = _calculateMean(data);
    double stdDev = _calculateStandardDeviation(data, mean);
    // 设置3-sigma阈值
    double threshold = 3 * stdDev;

    double perValue = (max + min) * 0.5;

    Iterable<double> filter = data.map((e) {
      bool isOutlier = (e - mean).abs() > threshold;
      bool isOutLimit = e > max || e < min;
      if (isOutlier || isOutLimit) {
        return perValue;
      }
      perValue = e;
      return e;
    });

    return filter.toList();
  }

  double _calculateMean(List<double> data) {
    double sum = 0.0;
    for (double value in data) {
      sum += value;
    }
    return sum / data.length;
  }

  double _calculateStandardDeviation(List<double> data, double mean) {
    double sumSquaredDiff = 0.0;
    for (double value in data) {
      double diff = value - mean;
      sumSquaredDiff += diff * diff;
    }
    double variance = sumSquaredDiff / data.length;
    return sqrt(variance);
  }
}
